package com.lc.rongzecaifu.fragment;

import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.lc.rongzecaifu.MyApplication;
import com.lc.rongzecaifu.activity.AccountManagementActivity;
import com.lc.rongzecaifu.activity.BorrowManageDetailActivity;
import com.lc.rongzecaifu.activity.FinancialActivity;
import com.lc.rongzecaifu.activity.FinancialServiceActivity;
import com.lc.rongzecaifu.activity.InvestManageDetailActivity;
import com.lc.rongzecaifu.activity.LoginActivity;
import com.lc.rongzecaifu.activity.MyAssetsActivity;
import com.lc.rongzecaifu.activity.NewWithDrawActivity;
import com.lc.rongzecaifu.activity.SettingsActivity;
import com.lc.rongzecaifu.activity.WithPayActivity;
import com.lc.rongzecaifu.beans.MEventBeans;
import com.lc.rongzecaifu.conn.JsonAccessToken;
import com.lc.rongzecaifu.conn.JsonUserinfo;
import com.lc.rongzecaifu.rongzecaifu.R;
import com.lc.rongzecaifu.toast.LovelyToast;
import com.lc.rongzecaifu.ui.RegistWebActivity;
import com.lc.rongzecaifu.view.BaseFragment;
import com.zcx.helper.bound.BoundView;
import com.zcx.helper.bound.BoundViewHelper;
import com.zcx.helper.http.AsyCallBack;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2017/3/16.
 */
public class MineFragment extends BaseFragment implements View.OnClickListener, View.OnLongClickListener {

    @BoundView(R.id.mine_setting_iv)
    private ImageView mine_setting_iv;//设置
    @BoundView(R.id.mine_login_show_ll)
    private LinearLayout mine_login_show_ll;//登录显示布局
    @BoundView(R.id.mine_head_iv)
    private SimpleDraweeView mine_head_iv;//头像
    @BoundView(R.id.mine_money_tv)
    private TextView mine_money_tv;//总资产
    @BoundView(R.id.mine_login_not_show_rl)
    private RelativeLayout mine_login_not_show_rl;//未登录显示布局
    @BoundView(R.id.main_login_tv)
    private TextView main_login_tv;//登录按钮
    @BoundView(R.id.mine_recharge_tv)
    private TextView mine_recharge_tv;//充值
    @BoundView(R.id.mine_withdraw_tv)
    private TextView mine_withdraw_tv;//提现


    @BoundView(R.id.mine_invest_ll)
    private LinearLayout mine_invest_ll;//投资管理
    @BoundView(R.id.mine_borrow_ll)
    private LinearLayout mine_borrow_ll;//借款管理
    @BoundView(R.id.mine_assets_ll)
    private LinearLayout mine_assets_ll;//我的资产
    @BoundView(R.id.mine_introduced_ll)
    private LinearLayout mine_introduced_ll;//荣泽介绍
    @BoundView(R.id.mine_server_ll)
    private LinearLayout mine_server_ll;//金融服务

    private int myType; //当主页 eventbus发送过来消息时候才可以跳转

    public static String userId;

    @BoundView(R.id.text_username)
    private TextView text_username;
    @BoundView(R.id.text_incode)
    private TextView text_incode;

    @BoundView(R.id.text_layout)
    private LinearLayout text_layout;

    String access_token;
    private PopupWindow popWindow2;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) inflater.inflate(R.layout.fragment_mine, null)));

        EventBus.getDefault().register(this);

        setListener();

        return view;
    }

    // 111 是mainActivity发送过来的  112是LoginActivity发送过来的, 0 setttingActivity退出时候发送的
    public void onEventMainThread(MEventBeans mEventBeans) {

        Log.e("---Mine", "EventBus 接收：" + mEventBeans.type);
        if (mEventBeans.type == 111) {

            startActivity(new Intent(getActivity(), RegistWebActivity.class).putExtra("url", MyApplication.myPreferences.readRegistUrl()));

        }

        myType = mEventBeans.type;

    }

    private void setListener() {

        mine_setting_iv.setOnClickListener(this);
        mine_head_iv.setOnClickListener(this);
        main_login_tv.setOnClickListener(this);
        mine_withdraw_tv.setOnClickListener(this);
        mine_recharge_tv.setOnClickListener(this);
        mine_invest_ll.setOnClickListener(this);
        mine_borrow_ll.setOnClickListener(this);
        mine_assets_ll.setOnClickListener(this);
        mine_introduced_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                //   startActivity(new Intent(getActivity(), FinancialActivity.class));
                new JsonAccessToken("index/services", new AsyCallBack<JsonAccessToken.Info>() {
                    @Override
                    public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                        if (info != null) {
                            if (!TextUtils.isEmpty(info.access_token)) {
                                Intent intent = new Intent();
//                intent.putExtra("url", JsonUserinfo.introduce_url);
                                intent.putExtra("url", "http://www.rongzecf.com/api/index/services/access_token/" + info.access_token);
//                intent2.putExtra("url", "http://www.rongzecf.com/api/index/about?access_token="+access_token);
                                intent.setClass(getContext(), FinancialActivity.class);
                                startActivity(intent);
                            } else {
                                //UtilToast.show(getActivity(), "安全验证失败！");
                                LovelyToast.makeText(getContext(), "安全验证失败！", 0, LovelyToast
                                        .SUCCESS, LovelyToast.SCALE);
                            }

                        }

                    }

                    @Override
                    public void onFail(String toast, int type) throws Exception {
                        super.onFail(toast, type);
                        // UtilToast.show(getActivity(), "安全验证失败！");
                        LovelyToast.makeText(getContext(), "安全验证失败！", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }
                }).execute(getActivity(), false);


            }
        });
        mine_server_ll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //   startActivity(new Intent(getActivity(), FinancialActivity.class));
                new JsonAccessToken("index/about", new AsyCallBack<JsonAccessToken.Info>() {
                    @Override
                    public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                        if (info != null) {
                            if (!TextUtils.isEmpty(info.access_token)) {
                              /*  Intent intent = new Intent();
//                intent.putExtra("url", JsonUserinfo.introduce_url);
                                intent.putExtra("url", "http://www.rongzecf.com/api/index/services/access_token/" +info.access_token);
//                intent2.putExtra("url", "http://www.rongzecf.com/api/index/about?access_token="+access_token);
                                intent.setClass(getContext(), FinancialActivity.class);
                                startActivity(intent);*/

                                //startActivity(new Intent(getActivity(), FinancialActivity.class));
//    intent2.putExtra("url", "http://www.rongzecf.com/api/index/about?access_token="+access_token);
                                Intent intent2 = new Intent();
                                // intent2.putExtra("url", JsonUserinfo.service_url);
                                intent2.putExtra("url", "http://www.rongzecf.com/api/index/about/access_token/" + info.access_token);
                                // intent2.putExtra("url", "http://www.rongzecf.com/api/index/about/" +access_token);
                                intent2.setClass(getContext(), FinancialServiceActivity.class);
                                startActivity(intent2);
                            } else {
                                //UtilToast.show(getActivity(), "安全验证失败！");
                                LovelyToast.makeText(getContext(), "安全验证失败！", 0, LovelyToast
                                        .SUCCESS, LovelyToast.SCALE);
                            }

                        }

                    }

                    @Override
                    public void onFail(String toast, int type) throws Exception {
                        super.onFail(toast, type);
                        // UtilToast.show(getActivity(), "安全验证失败！");
                        LovelyToast.makeText(getContext(), "安全验证失败！", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }
                }).execute(getActivity(), false);


            }
        });
        text_incode.setOnClickListener(this);
    }

    @Override
    public void onResume() {

        if (!TextUtils.isEmpty(MyApplication.myPreferences.readUid())) {

            mine_login_not_show_rl.setVisibility(View.GONE);
            mine_login_show_ll.setVisibility(View.VISIBLE);
            text_layout.setVisibility(View.VISIBLE);
            getAccessToken();

        } else {

            mine_login_not_show_rl.setVisibility(View.VISIBLE);
            mine_login_show_ll.setVisibility(View.GONE);
            text_layout.setVisibility(View.GONE);
        }

        super.onResume();
    }

    @Override
    public void onClick(View v) {

        if (v.getId() != R.id.main_login_tv && TextUtils.isEmpty(MyApplication.myPreferences.readUid())) {
            //  ToastUtils.show(getActivity(), "请登录后再操作！");
            LovelyToast.makeText(getContext(), "请登录后再操作！", 0, LovelyToast
                    .SUCCESS, LovelyToast.SCALE);
            return;
        }
        switch (v.getId()) {

            case R.id.mine_setting_iv://设置

                startActivity(new Intent(getActivity(), SettingsActivity.class));

                break;

            case R.id.mine_head_iv://头像

                startActivity(new Intent(getActivity(), AccountManagementActivity.class));

                break;

            case R.id.main_login_tv://登录按钮

                startActivity(new Intent(getActivity(), LoginActivity.class));

                break;

            case R.id.mine_recharge_tv://充值按钮

                //false为充值
                //    startActivity(new Intent(getActivity(), WithdrawOrRechargeActivity.class).putExtra("mode", false));

                if (MyApplication.myPreferences.readStatus().equals("9")) {
                    showPopupWindow2(mine_recharge_tv);
                } else {
                    startActivity(new Intent(getActivity(), WithPayActivity.class));
                }


                break;

            case R.id.mine_withdraw_tv://提现

                //true为提现
                //  startActivity(new Intent(getActivity(), WithdrawOrRechargeActivity.class).putExtra("mode", true));
                if (MyApplication.myPreferences.readStatus().equals("9")) {
                    showPopupWindow2(mine_recharge_tv);
                } else {
                    startActivity(new Intent(getActivity(), NewWithDrawActivity.class));
                }
                break;

            case R.id.mine_invest_ll://投资管理

                startActivity(new Intent(getActivity(), InvestManageDetailActivity.class));

                break;

            case R.id.mine_borrow_ll://借款管理
                startActivity(new Intent(getActivity(), BorrowManageDetailActivity.class));
                //  startActivity(new Intent(getActivity(), BorrowManageDetailActivity2.class));
                break;

            case R.id.mine_assets_ll://我的资产

                startActivity(new Intent(getActivity(), MyAssetsActivity.class));

                break;

           /* case R.id.mine_introduced_ll://荣泽介绍

                //   startActivity(new Intent(getActivity(), FinancialActivity.class));

                Intent intent = new Intent();
                intent.putExtra("url", JsonUserinfo.introduce_url);
                intent.setClass(getContext(), FinancialActivity.class);
                startActivity(intent);

                break;
*/
          /*  case R.id.mine_server_ll://金融服务

                //startActivity(new Intent(getActivity(), FinancialActivity.class));

                Intent intent2 = new Intent();
                intent2.putExtra("url", JsonUserinfo.service_url);
                intent2.setClass(getContext(), FinancialServiceActivity.class);
                startActivity(intent2);

                break;
*/
            //TextVIew长按复制
            case R.id.text_incode:
                ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
//将文本数据复制到剪贴板
                cm.setText(text_incode.getText().toString().trim());
                cm.getText();
                break;


        }
    }

    private void getAccessToken() {
        new JsonAccessToken("user/userinfo", new AsyCallBack<JsonAccessToken.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonAccessToken.Info info) throws Exception {
                if (info != null) {
                    if (!TextUtils.isEmpty(info.access_token)) {
                        onGetUserInfo(info.access_token);
                        access_token = info.access_token;
                    } else {
                        //UtilToast.show(getActivity(), "安全验证失败！");
                        LovelyToast.makeText(getContext(), "安全验证失败！", 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);
                    }

                }

            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                super.onFail(toast, type);
                // UtilToast.show(getActivity(), "安全验证失败！");
                LovelyToast.makeText(getContext(), "安全验证失败！", 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }
        }).execute(getActivity(), false);
    }

    private void onGetUserInfo(String access_token) {
        new JsonUserinfo(access_token, MyApplication.myPreferences.readUid(), new AsyCallBack<JsonUserinfo.Info>() {
            @Override
            public void onSuccess(String toast, int type, JsonUserinfo.Info info) throws Exception {
                if (info != null) {
                    if (TextUtils.isEmpty(info.status)) {

                        MyApplication.myPreferences.saveUid(info.id);

                        MyApplication.myPreferences.saveUserName(info.user_name);

                        MyApplication.myPreferences.saveUser_email(info.user_email);

                        MyApplication.myPreferences.saveUser_phone(info.user_phone);

                        MyApplication.myPreferences.saveSex(info.sex);

                        MyApplication.myPreferences.saveReal_name(info.real_name);

                        MyApplication.myPreferences.saveIdcard(info.idcard);

                        MyApplication.myPreferences.saveMoney_freeze(info.money_freeze);

                        MyApplication.myPreferences.saveMoney_collect(info.money_collect);

                        MyApplication.myPreferences.saveAccount_money(info.account_money);

                        MyApplication.myPreferences.saveMoney_experience(info.money_experience);

                        MyApplication.myPreferences.saveAll_money(info.all_money);

                        MyApplication.myPreferences.saveUserpic(info.userpic);

                        MyApplication.myPreferences.saveId_status(info.id_status);

                        MyApplication.myPreferences.saveVip_status(info.vip_status);

                        MyApplication.myPreferences.savePhone_status(info.phone_status);

                        MyApplication.myPreferences.saveEmail_status(info.email_status);

                        MyApplication.myPreferences.savePin_pass(info.pin_pass);
                        MyApplication.myPreferences.saveNickName(info.nick_name);
                        MyApplication.myPreferences.saveIncode(info.incode);
                        mine_money_tv.setText(MyApplication.myPreferences.readAll_money());

                        mine_head_iv.setImageURI(Uri.parse(MyApplication.myPreferences.readUserpic()));
                        text_username.setText(MyApplication.myPreferences.readUserName());
                        text_incode.setText("推荐码：" + MyApplication.myPreferences.readIncode());
                        MyApplication.myPreferences.saveStatus(info.status);
                        MyApplication.myPreferences.saveRegistUrl(info.url);

                    } else if (info.status.equals("9")) {
                        //    startActivity(new Intent(getActivity(), RegistWebActivity.class).putExtra("url", info.url));
                      /*  Intent intent = new Intent();
                        intent.putExtra("url", info.url);
                        intent.setClass(getActivity(), RegistWebActivity.class);
                        startActivity(intent);*/
                       /* LovelyToast.makeText(getContext(), JsonUserinfo.TOAST, 0, LovelyToast
                                .SUCCESS, LovelyToast.SCALE);*/
                        MyApplication.myPreferences.saveRegistUrl(info.url);
                        MyApplication.myPreferences.saveStatus(info.status);
                        MyApplication.myPreferences.saveUserName(info.user_name);
                        MyApplication.myPreferences.saveUser_phone(info.user_phone);
                        MyApplication.myPreferences.saveIncode(info.incode);
                        text_incode.setText(info.incode);
                        text_username.setText(info.user_name);
                        mine_money_tv.setText("0.0");
                        EventBus.getDefault().post(9);
                        return;
                    }
                }
            }

            @Override
            public void onFail(String toast, int type) throws Exception {
                // UtilToast.show(getActivity(), JsonUserinfo.TOAST);
                LovelyToast.makeText(getContext(), JsonUserinfo.TOAST, 0, LovelyToast
                        .SUCCESS, LovelyToast.SCALE);
            }

        }

        ).

                execute(getActivity(),

                        false);

    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    public boolean onLongClick(View v) {
        switch (v.getId()) {
            case R.id.text_incode:

                ClipboardManager cm = (ClipboardManager) getActivity().getSystemService(Context.CLIPBOARD_SERVICE);
//将文本数据复制到剪贴板
                cm.setText(text_incode.getText().toString().trim());
                cm.getText();
                break;
        }


        return false;
    }


    private void showPopupWindow2(View parent) {
        if (popWindow2 == null) {
            View view = BoundViewHelper.boundView(this, MyApplication.scaleScreenHelper.loadView((ViewGroup) LayoutInflater.from(getActivity())
                    .inflate(R.layout.dialog_kaihu, null)));
            //LayoutParams相当于一个Layout的信息包，它封装了Layout的位置、高、宽等信息。
            popWindow2 = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
            initPop2(view);
        }
        //设置动画效果
        popWindow2.setAnimationStyle(android.R.style.Animation_Dialog);
        //获取popwindow焦点
        popWindow2.setFocusable(true);
        //设置popwindow如果点击外面区域，便关闭。
        popWindow2.setOutsideTouchable(true);
        popWindow2.setBackgroundDrawable(new BitmapDrawable());
        //实现软键盘不自动弹出,ADJUST_RESIZE属性表示Activity的主窗口总是会被调整大小，从而保证软键盘显示空间。
        popWindow2.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        //设置popwindow显示位置
        popWindow2.showAtLocation(parent, Gravity.CENTER, 0, 0);
    }

    public void initPop2(View view) {
        TextView tv01 = (TextView) view.findViewById(R.id.dl_tv_01);//拍照
        TextView tv02 = (TextView) view.findViewById(R.id.dl_tv_02);//相册


        final LinearLayout linear_dialog3 = (LinearLayout) view.findViewById(R.id.linear_dialog3);

        tv01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                popWindow2.dismiss();
                popWindow2 = null;

            }
        });
        tv02.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {

                Intent intent = new Intent();
                intent.putExtra("url", MyApplication.myPreferences.readRegistUrl());
                intent.setClass(getActivity(), RegistWebActivity.class);
                startActivity(intent);
                popWindow2.dismiss();
            }
        });
    }


}
